package com.xwder.nettyclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

/**
 * @author xwder
 * @date 2021/3/31 14:47
 **/
public class NettyClient {

    private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);

    private final String host;
    private final int port;
    private EventLoopGroup group;
    private Bootstrap bootstrap;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        NettyClient nettyClient = this;
        group = new NioEventLoopGroup();
        try {
            bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ClientInitializer(nettyClient));

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //得到channel
            Channel channel = channelFuture.channel();
            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    logger.info("客户端启动成功,地址:{}", channel.localAddress().toString().substring(1));
                }
            });

            //客户端需要输入信息，创建一个扫描器
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                //通过channel 发送到服务器端
                channel.writeAndFlush(msg + "\r\n");
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    /**
     * 重新连接
     */
    public void reConnect() {
        logger.debug("Netty远程服务器host:{},端口:{}", host, port);
        ChannelFuture channelFuture = bootstrap.connect();
        channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                logger.debug("与远程服务器连接成功");
            } else {
                logger.debug("尝试重新连接远程服务器");
                Thread.sleep(2000);
                reConnect();
            }
        });
    }

    public static void main(String[] args) throws Exception {
//        new NettyClient("119.29.136.137", 6666).run();
         new NettyClient("127.0.0.1", 6666).run();
    }
}
